package matrix.螺旋矩阵;

import java.util.ArrayList;
import java.util.List;

//给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
// 
// 示例 1： 
// 
//输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
//输出：[1,2,3,6,9,8,7,4,5]
// 
// 示例 2： 
// 
//输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
//输出：[1,2,3,4,8,12,11,10,9,5,6,7]
// 
// 
// 提示： 
// 
// m == matrix.length 
// n == matrix[i].length 
// 1 <= m, n <= 10 
// -100 <= matrix[i][j] <= 100 
// 
// Related Topics 数组 矩阵 模拟 👍 1955 👎 0
public class Solution {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();
        /**
         * 思路：
         * 运动轨迹 右 -> 下 -> 左 -> 右
         * 方向结束条件：1.当到达了边界时 2. 当到达了已经路过的元素
         */
        int rowLen = matrix[0].length,
                columnLen = matrix.length,
                laps = 0,
                row = 0,
                column = 0,
                maxLaps = Math.min(rowLen, columnLen) / 2;
        while (laps <= maxLaps) {
            while (right(laps, column, rowLen)) {
                ans.add(matrix[row][column]);
                column++;
            }
            while (down(laps, row, columnLen)) {
                ans.add(matrix[row][column]);
                row++;
            }
            while (left(laps, column)) {
                ans.add(matrix[row][column]);
                column--;
            }
            while (up(laps, row)) {
                ans.add(matrix[row][column]);
                row--;
            }
            laps++;
        }
        if (Math.min(rowLen,columnLen)  % 2 == 1) {
            ans.add(matrix[row][column]);
        }
        return ans;
    }

    public boolean right(int laps, int currentColumn, int rowLen) {
        if (currentColumn <= rowLen - laps  -1) {
            return true;
        } else {
            return false;
        }
    }

    public boolean down(int laps, int currentRow, int columnLen) {
        if (currentRow <= columnLen - laps -1 ) {
            return true;
        } else {
            return false;
        }
    }

    public boolean left(int laps, int currentColumn) {
        if (currentColumn - laps >=  0) {
            return true;
        } else {
            return false;
        }
    }

    public boolean up(int laps, int currentRow) {
        if (currentRow - laps >= 0) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.spiralOrder(new int[][]{
//                {1,2,3,4},{10,11,12,5},{9,8,7,6}
                {1, 2, 3}, {8, 9, 4}, {7, 6, 5}
//                {1,2}
        }));
    }

}
